﻿using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Infrastructure.Utility.Core.PDF
{
    /// <summary>
    /// v2版本模板电子凭证
    /// </summary>
    public abstract class TemplatePdfBaseBuilder
    {


        protected readonly static BaseFont baseFont = BaseFont.CreateFont(
                            Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "PDF/SIMSUN.TTC,0"),
                            BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        protected readonly Font font = new Font(baseFont, 14, 0, BaseColor.Black);
        protected readonly Font small_font = new Font(baseFont, 12, 0, BaseColor.Black);

        protected PdfPTable table = new PdfPTable(8) { WidthPercentage = 100 };

        //pageSize.BackgroundColor = new Color(0xFF, 0xFF, 0xDE);
        protected Document document = new Document();
        // document.SetPageSize(new Rectangle(600,500));PageSize.A3


        protected TemplatePdfBaseBuilder(OrderInfo orderInfo, CustomerInfo customerInfo, ReceiptInfo receiptInfo, OrderItemInfo orderItemInfo,
  FromOrderInfo refundInfo, ElecCertConfig config, string pathSeal)
        {
            this.OrderInfo = orderInfo;
            this.CustomerInfo = customerInfo;
            this.ReceiptInfo = receiptInfo;
            this.OrderInfo = OrderInfo;
            this.OrderItemInfo = orderItemInfo;
            this.FromInfo = refundInfo;
            this.Config = config;
            this.FullPathSeal = pathSeal;
            var height = 900;
            if (orderInfo.TransferInAmount != 0) height += 50;
            document.SetPageSize(new Rectangle(600, height + (OrderInfo.ReceiptInfos.Count * 40)));
            //document.SetPageSize(new Rectangle(600, 950));
        }

        /// <summary>
        /// 服务费电子凭证-顶部
        /// </summary>
        /// <returns></returns>
        protected virtual Document GetHeader()
        {

            PdfPCell cell_title = new(new Phrase("升学服务类电子凭证", font))
            {
                Colspan = 8,
                Rowspan = 1,
                Padding = 5,
                BorderWidthBottom = 0
            };
            cell_title.BorderWidthBottom = 0;
            cell_title.HorizontalAlignment = Element.ALIGN_CENTER;
            cell_title.VerticalAlignment = Element.ALIGN_MIDDLE;
            table.AddCell(cell_title);


            PdfPCell cell_number = new(new Phrase($"No:{OrderInfo.OrderNumber.Substring(2)}", font))
            {
                Colspan = 8,
                Rowspan = 1,
                Padding = 5,
                BorderWidthBottom = 0
            };
            cell_number.BorderWidthBottom = 0;
            cell_number.HorizontalAlignment = Element.ALIGN_RIGHT;
            cell_number.VerticalAlignment = Element.ALIGN_CENTER;
            table.AddCell(cell_number);

            return document;
        }


        #region 数据信息
        /// <summary> 
        /// 客户的信息数据
        /// </summary>
        protected CustomerInfo CustomerInfo { get; set; }

        /// <summary>
        /// 订单的信息数据
        /// </summary>

        protected OrderInfo OrderInfo { get; set; }

        /// <summary>
        /// 收据的信息数据
        /// </summary>

        protected ReceiptInfo ReceiptInfo { get; set; }

        /// <summary>
        /// 商品的信息数据
        /// </summary>

        protected OrderItemInfo OrderItemInfo { get; set; }

        /// <summary>
        /// 退费、降转的信息数据
        /// </summary>
        protected FromOrderInfo FromInfo { get; set; }

        /// <summary>
        /// 电子凭证配置
        /// </summary>
        protected ElecCertConfig Config { get; set; }

        /// <summary>
        /// 公章全路径
        /// </summary>
        protected string FullPathSeal { get; set; }

        #endregion

        /// <summary>
        /// 学员信息
        /// </summary>
        protected virtual void GetCustomerInfo()
        {
            var cellList = new List<PdfPCell>()
            {
                new PdfPCell(new Phrase("姓名", font)){ Colspan=1 },
                new PdfPCell(new Phrase(CustomerInfo.Name, font)) { Colspan=1 },

                new PdfPCell(new Phrase("工作单位", font)){ Colspan=1 }  ,
                new PdfPCell(new Phrase(CustomerInfo.WorkUnit, font)){ Colspan=5}
             };

            for (int i = 0; i < cellList.Count; i++)
            {
                if (i > 0)
                    cellList[i].BorderWidthLeft = 0;

                cellList[i].Padding = 5;
                cellList[i].NoWrap = true;

                cellList[i].HorizontalAlignment = Element.ALIGN_CENTER;
                cellList[i].VerticalAlignment = Element.ALIGN_MIDDLE;
                cellList[i].BorderWidthBottom = 0;
                table.AddCell(cellList[i]);
            }
            var cellList2 = new List<PdfPCell>()
            {
                new PdfPCell(new Phrase("性别", font)){ Colspan=1 },
                new PdfPCell(new Phrase(CustomerInfo.Gender, font)){ Colspan=1,BorderWidthLeft=0 } ,

                new PdfPCell(new Phrase("电话", font)){ Colspan=1,BorderWidthLeft=0 },
                new PdfPCell(new Phrase(CustomerInfo.Mobile, font)){ Colspan=2 , BorderWidthLeft = 0},

                new PdfPCell(new Phrase("居住城市", font)){ Colspan=1  ,BorderWidthLeft=0 },
                new PdfPCell(new Phrase(CustomerInfo.City, font)){ Colspan=2,BorderWidthLeft=0 },

                new PdfPCell(new Phrase("身份证号", font)){ Colspan=1},
                new PdfPCell(new Phrase(CustomerInfo.IdCard??"---", font)){ Colspan=3,BorderWidthLeft = 0 },
                new PdfPCell(new Phrase("紧急联系方式", font)){ Colspan=2,BorderWidthLeft = 0 },
                new PdfPCell(new Phrase(CustomerInfo.TelePhone??"---------", font)){ Colspan=2,BorderWidthLeft = 0 }
             };
            cellList2.ForEach(c =>
            {

                c.Padding = 5;
                c.NoWrap = true;
                c.HorizontalAlignment = Element.ALIGN_CENTER;
                c.VerticalAlignment = Element.ALIGN_MIDDLE;
                c.BorderWidthBottom = 0;

                table.AddCell(c);
            });

        }


        /// <summary>
        /// 服务费是 录取院校
        /// </summary>
        protected virtual void GetMajorTypeInfo()
        {
            PdfPCell cellExamInfo = new(new Phrase("录取院校", font))
            {
                Colspan = 1,
                Rowspan = 1,
                Padding = 5,
                BorderWidthBottom = 0
            };
            cellExamInfo.BorderWidthBottom = 0;
            cellExamInfo.HorizontalAlignment = Element.ALIGN_CENTER;
            cellExamInfo.VerticalAlignment = Element.ALIGN_MIDDLE;
            table.AddCell(cellExamInfo);


            var cell = new PdfPCell(new Phrase($"{OrderItemInfo.FirstSchool}", font))
            {
                Padding = 5,
                Rowspan = 1,
                Colspan = 7,
                BorderWidthLeft = 0,
                BorderWidthBottom = 0,
                VerticalAlignment = Element.ALIGN_MIDDLE
            };
            // cell.SetLeading(1, 1.3f);
            table.AddCell(cell);
        }


        /// <summary>
        /// 服务费  缴费信息
        /// </summary>
        protected virtual void GetPayInfo()
        {

            PdfPCell cellPayInfoInfo = new(new Phrase("缴费信息", font))
            {
                Colspan = 1,
                Rowspan = 3,
                BorderWidthBottom = 0,
                HorizontalAlignment = Element.ALIGN_CENTER,
                VerticalAlignment = Element.ALIGN_MIDDLE
            };
            table.AddCell(cellPayInfoInfo);



            string allAmount = $@"应缴费总金额：{ConvertToChineseAndLowerString(OrderInfo.OrderTotal)}";


            List<PdfPCell> listExamInfoItems = new List<PdfPCell>()
            {
               new PdfPCell(new Phrase($@"{allAmount}", small_font)) { Rowspan = 1}
             };

            string str = $@"杂费（{string.Join(",", OrderItemInfo.ItemMixFees.Select(c => c.Name))}）";
            listExamInfoItems.Add(new PdfPCell(new Phrase(str.ToString(), small_font)) { Rowspan = 1 });

            string payInfoText = string.Empty;
            if (OrderInfo.OrderType.ToLower()!="zc")
            {
                StringBuilder str2 = new StringBuilder();

                if (OrderInfo.TransferInAmount > 0)
                    str2.Append($"转入金额：{ConvertToChineseAndLowerString(OrderInfo.TransferInAmount)}");

                if (OrderInfo.TransferInAmount >= (decimal)OrderItemInfo.Amount / 100)
                    str2.Append($"缴费类型：（全款） ");
                else
                    str2.Append($"缴费类型：（部分款） ");

                str2.Append($"缴费时间：{OrderInfo.CreateTime.ToString("yyyy-MM-dd")}");

                str2.Append($"\n备注：{OrderInfo.TransferMessage}");
                payInfoText = str2.ToString();
            }  
            foreach (var item in OrderInfo.ReceiptInfos)
            {
                if (!string.IsNullOrWhiteSpace(payInfoText))
                    payInfoText += "\n";

                payInfoText += $@"缴费金额：{ConvertToChineseAndLowerString(item.ThisPay)} 缴费类型：({(item.ThisPay >= OrderInfo.AllNeedPay ? "全款" : "部分款")}) 缴费时间：{item.ReceiptTime}";
            }
            if (!string.IsNullOrWhiteSpace(payInfoText))
                payInfoText += "\n";
            payInfoText += $"欠费金额：{ConvertToChineseAndLowerString(OrderInfo.ArrearsAmount)}";
            listExamInfoItems.Add(new PdfPCell(new Phrase(payInfoText, small_font)) { Rowspan = 1 });

            listExamInfoItems.ForEach(c =>
            {
                c.Padding = 5;
                //c.SetLeading(1, 1.3f);
                c.Colspan = 7;
                c.BorderWidthLeft = 0;
                c.BorderWidthBottom = 0;
                table.AddCell(c);
            });

        }



        #region 金额数字转为大写 和 格式化
        /// <summary>
        /// 人民币金额转汉字大写
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        protected string ConvertToChinese(decimal number)
        {
            if (number == 0)
            {
                return "零元";
            }

            var s = number.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
            var d = Regex.Replace(s, @"((?<=-|^)[^1-9]*)|((?'z'0)[0A-E]*((?=[1-9])|(?'-z'(?=[F-L\.]|$))))|((?'b'[F-L])(?'z'0)[0A-L]*((?=[1-9])|(?'-z'(?=[\.]|$))))", "${b}${z}");
            var r = Regex.Replace(d, ".", m => "负元空零壹贰叁肆伍陆柒捌玖空空空空空空空分角拾佰仟万亿兆京垓秭穰"[m.Value[0] - '-'].ToString());
            return r;
        }

        /// <summary>
        /// 人民币金额转小写格式化（精确到小数点后两位）
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        protected string ConvertToLowerString(decimal number)
        {
            return string.Format("¥{0:N2}", number);
        }

        /// <summary>
        /// 人民币金额转汉字大写+小写格式化（精确到小数点后两位）
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        protected string ConvertToChineseAndLowerString(decimal number)
        {
            return $"{ConvertToChinese(number)}（{ConvertToLowerString(number)}）";
        }
        #endregion
    }
}
